//
//  AliPay.swift
//  Aiwei
//
//  Created by zhu xietong on 2018/1/5.
//  Copyright © 2018年 zhu xietong. All rights reserved.
//

import UIKit
import AlipaySDK

public enum AliPayResult:Int
{
    case ok = 0
    case canle = -2
    case failed = -1
    case notice_failed = 4
    
}

public class MOSDK0002:MOSDK{
    public override func begin() {
        DoPay.share.add(realization: FastAliPay.shared)
        HandleOpenURL.add(owner: AliURLOwner.share)
    }
}

public class AliURLOwner:NSObject,MoURLOwnerRealization{
    public var schemes: [String] = []
    
    public func handleOpenUniversalLink(userActivity: NSUserActivity) -> Bool {
        return false
    }
    
    
    static var _share:AliURLOwner? = nil
    static var share:AliURLOwner{
        get{
            guard let share = _share else {
                let share = AliURLOwner()
                _share = share
                return share
            }
            return share
        }
    }
    
    public var plat: String = "ali"
    public var hosts: [String] = ["safepay"]
    public func handle(url: URL, resource: String) -> Bool {
//        print("alipay=-----",url,url.host)
        if let host = url.host{
            if host == "safepay"{
            AlipaySDK.defaultService().processOrder(withPaymentResult: url, standbyCallback: { (info) in
                                           if let dict = info?.mutable_dictionary
                                           {
                       //                        "收到阿里支付".alert()
                                               FastAliPay.shared.dealCallBack(result: dict)
                           }
                       })
            }
        }
        return true
    }
}


public class FastAliPay: NSObject,MoPayRealization{
    public var name: String = "支付宝"
    
    public var ID: String = "ali"
    
    public func pay(pay_id: String, task_type: String, _ sign: NSMutableDictionary, finish_block: @escaping (DoPayReuslt, String, String) -> Void) {
        
        
        paySigner(sign["sign",""]) { (_result, msg) in
            switch _result{
            case .ok:
                finish_block(.ok(.ali), task_type, pay_id)
            case .canle:
                finish_block(.canle(.ali), task_type, pay_id)
            case .failed:
                finish_block(.failed(.ali,msg), task_type, pay_id)
            default:
                finish_block(.failed(.ali,msg), task_type, pay_id)
            }
        }
    }
    
    

    public struct Static {
        static var instance:FastAliPay? = nil
    }

    public class var  shared:FastAliPay {
        get{
            if Static.instance == nil{
                Static.instance = FastAliPay()
            }
            return Static.instance!
        }
    }

    public required override init() {
        super.init()
    }
    
    public func dealCallBack(result:NSMutableDictionary)
    {

        if result["resultStatus","0"] == "9000"
        {
            finish_block(.ok,"支付成功")
            return
        }
        else if result["resultStatus","0"] == "6001"
        {
            self.finish_block(.canle,"支付已取消")
            return
        }
        finish_block(AliPayResult.failed,"支付失败")

    }

    public var finish_block:((AliPayResult,String)-> Void) = {_,_ in}
    public var checkTime:Int = 0
    public func paySigner(_ signedString:String,finish_block:@escaping (AliPayResult,String)-> Void)
    {
        
        self.checkTime = 0
        self.finish_block = finish_block

        weak var wself = self
        //        AlipaySDK.defaultService
        let scheme = "\(SDKConfig.ZifuBao.scheme)"
        
        AlipaySDK.defaultService().payOrder(signedString, fromScheme: scheme) { (result:[AnyHashable : Any]?) in
            wself?.checkTime += 1
            
//            print("--nnn====ss====s===sdds|\(result)")
            if let dict = result?.mutable_dictionary
            {

                if dict["resultStatus","0"] == "9000"
                {
                    if let o_id = UserDefaults.standard.object(forKey: "ly_zfb_order_id")
                    {
                        wself?.finish_block(.ok,"支付成功")

                    }
                    return
                }
                else if dict["resultStatus","0"] == "6001"
                {
                    wself?.finish_block(.canle,"支付取消")
                    return
                }
                wself?.finish_block(AliPayResult.failed,"支付失败")

            }


        }


    }


    
    
}
